import os
import pandas as pd
from pathlib import Path
import re
import sys

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，支持开发环境和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包环境
        base_path = sys._MEIPASS
    else:
        # 开发环境
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

def ensure_output_directory(folder_name):
    """确保输出目录存在"""
    data_dir = Path("data")
    output_dir = data_dir / "output" / folder_name
    output_dir.mkdir(parents=True, exist_ok=True)
    return output_dir

def load_excel_file(file_path, header_row=1):
    """加载Excel文件，从指定行开始作为列名"""
    try:
        return pd.read_excel(file_path, header=header_row)
    except Exception as e:
        print(f"Error loading {file_path}: {str(e)}")
        return None

def get_source_folders():
    """获取source文件夹下的所有文件夹"""
    data_dir = Path("data")
    source_dir = data_dir / "source"
    
    if not source_dir.exists():
        print(f"Source directory not found: {source_dir}")
        return []
    
    return [f for f in source_dir.iterdir() if f.is_dir()]

def load_filtered_bank_data(folder_path):
    """加载银行流水数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    
    # 读取银行流水数据
    bank_file = folder_path / "银行流水数据库.xlsx"
    if not bank_file.exists():
        print(f"银行流水文件不存在: {bank_file}")
        return None
    
    bank_df = load_excel_file(bank_file, header_row=0)
    if bank_df is None or bank_df.empty:
        print("银行流水文件为空或格式错误")
        return None
    
    # 检查银行流水文件的列名
    required_bank_columns = ['名称', '交易对方名称', '证件号码', '交易对方证件号码', '借贷标志']
    missing_bank_columns = [col for col in required_bank_columns if col not in bank_df.columns]
    if missing_bank_columns:
        print(f"银行流水文件缺少必要的列: {missing_bank_columns}")
        print(f"当前列名: {list(bank_df.columns)}")
        return None

    print(f"成功加载银行流水数据，共 {len(bank_df)} 条记录")
    return bank_df

def analyze_relative_network(folder_path, filtered_bank_df):
    """分析指定文件夹中的人员关系网络数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    
    # 读取亲属关系文件，从第二行开始作为列名
    relative_file = folder_path / "亲属关系.xlsx"
    if not relative_file.exists():
        print(f"[亲属关系分析] {folder_name}: 亲属关系文件不存在: {relative_file}")
        return None, None
    
    relative_df = load_excel_file(relative_file, header_row=1)  # 从第二行开始读取列名
    if relative_df is None or relative_df.empty:
        print(f"[亲属关系分析] {folder_name}: 亲属关系文件为空或格式错误")
        return None, None
    
    # 检查亲属关系文件的列名
    required_relative_columns = ['名称', '身份证号码', '关系']
    missing_relative_columns = [col for col in required_relative_columns if col not in relative_df.columns]
    if missing_relative_columns:
        print(f"[亲属关系分析] {folder_name}: 亲属关系文件缺少必要的列: {missing_relative_columns}")
        print(f"当前列名: {list(relative_df.columns)}")
        return None, None

    # 准备亲属关系数据
    relationship_df = relative_df[['名称', '关系']].copy()
    relationship_df['关系类型'] = '亲属'
    relationship_df['公司名称'] = None  # 添加空的公司名称列
    print(f"[亲属关系分析] {folder_name}: 找到 {len(relationship_df)} 条亲属关系数据")

    # 获取所有需要匹配的名称和身份证号码
    names_to_match = set(relative_df['名称'].dropna().unique())
    id_numbers_to_match = set(relative_df['身份证号码'].dropna().unique())
    
    if not names_to_match and not id_numbers_to_match:
        print(f"[亲属关系分析] {folder_name}: 未找到有效的名称或身份证号码数据")
        return None, relationship_df
    
    # 创建名称到关系的映射
    name_to_relationship = {}
    for _, row in relative_df.iterrows():
        name = str(row['名称'])
        relationship = str(row['关系'])
        name_to_relationship[name] = relationship
    
    # 初始化结果DataFrame
    result_rows = []
    
    # 遍历银行流水数据
    for _, row in filtered_bank_df.iterrows():
        name = str(row['名称'])
        counterparty_name = str(row['交易对方名称'])
        id_number = str(row['证件号码'])
        counterparty_id = str(row['交易对方证件号码'])
        
        # 检查当前行的名称是否在亲属关系表中
        name_in_relative = name in names_to_match
        counterparty_name_in_relative = counterparty_name in names_to_match
        id_in_relative = id_number in id_numbers_to_match
        counterparty_id_in_relative = counterparty_id in id_numbers_to_match
        
        # 如果交易双方都在亲属关系表中，添加到结果中
        if (name_in_relative or id_in_relative) and (counterparty_name_in_relative or counterparty_id_in_relative):
            result_rows.append(row)
    
    # 创建结果DataFrame
    if result_rows:
        result_df = pd.DataFrame(result_rows)
        
        # 初始化关系列
        result_df['关系'] = None
        
        # 处理亲属关系
        for idx, row in result_df.iterrows():
            name = str(row['名称'])
            counterparty_name = str(row['交易对方名称'])
            
            # 获取双方的关系
            name_relationship = name_to_relationship.get(name)
            counterparty_relationship = name_to_relationship.get(counterparty_name)
            
            # 只有当双方关系都是"本人"时，才标记为"本人"
            if name_relationship == '本人' and counterparty_relationship == '本人':
                result_df.loc[idx, '关系'] = '本人'
            # 否则使用非本人的那一方的关系
            elif name_relationship != '本人' and name_relationship is not None:
                result_df.loc[idx, '关系'] = name_relationship
            elif counterparty_relationship != '本人' and counterparty_relationship is not None:
                result_df.loc[idx, '关系'] = counterparty_relationship
        
        # 删除关系为空的行
        result_df = result_df.dropna(subset=['关系'])
        
        # 添加关系类型列
        result_df['关系类型'] = '亲属'
        print(f"[亲属关系分析] {folder_name}: 找到 {len(result_df)} 条匹配记录")
        return result_df, relationship_df
    else:
        print(f"[亲属关系分析] {folder_name}: 未找到匹配的亲属关系交易记录")
        return None, relationship_df

def analyze_employment_network(folder_path, filtered_bank_df):
    """分析指定文件夹中的任职单位关系网络数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    
    # 读取任职单位文件
    employment_file = folder_path / "任职单位.xlsx"
    if not employment_file.exists():
        print(f"[任职单位分析] {folder_name}: 任职单位文件不存在: {employment_file}")
        return None, None
    
    employment_df = load_excel_file(employment_file, header_row=0)
    if employment_df is None or employment_df.empty:
        print(f"[任职单位分析] {folder_name}: 任职单位文件为空或格式错误")
        return None, None
    
    # 检查任职单位文件的列名
    if '任职单位' not in employment_df.columns:
        print(f"[任职单位分析] {folder_name}: 任职单位文件缺少必要的列: 任职单位")
        print(f"当前列名: {list(employment_df.columns)}")
        return None, None

    # 准备任职单位关系数据
    relationship_df = pd.DataFrame()
    relationship_df['名称'] = employment_df['任职单位']
    relationship_df['关系'] = '任职单位'
    relationship_df['关系类型'] = '任职单位'
    relationship_df['公司名称'] = None  # 添加空的公司名称列
    print(f"[任职单位分析] {folder_name}: 找到 {len(relationship_df)} 条任职单位关系数据")

    # 获取所有任职单位
    employment_units = set(employment_df['任职单位'].dropna().unique())
    
    # 筛选任职单位出现在交易记录中的行
    result_rows = []
    for _, row in filtered_bank_df.iterrows():
        name = str(row['名称'])
        counterparty_name = str(row['交易对方名称'])
        
        # 检查名称或交易对方名称是否在任职单位列表中
        if any(unit in name for unit in employment_units) or any(unit in counterparty_name for unit in employment_units):
            result_rows.append(row)
    
    if not result_rows:
        print(f"[任职单位分析] {folder_name}: 未找到与任职单位相关的交易记录")
        return None, relationship_df
    
    # 创建结果DataFrame
    result_df = pd.DataFrame(result_rows)
    
    # 添加关系信息
    result_df['关系'] = '任职单位'
    result_df['关系类型'] = '任职单位'
    
    print(f"[任职单位分析] {folder_name}: 找到 {len(result_df)} 条匹配记录")
    return result_df, relationship_df

def analyze_specific_relationships(folder_path, filtered_bank_df):
    """分析指定文件夹中的特定关系人网络数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    
    # 读取特定关系人文件，从第一行开始作为列名
    specific_file = folder_path / "特定关系人.xlsx"
    if not specific_file.exists():
        print(f"[特定关系人分析] {folder_name}: 特定关系人文件不存在: {specific_file}")
        return None, None
    
    specific_df = load_excel_file(specific_file, header_row=0)
    if specific_df is None or specific_df.empty:
        print(f"[特定关系人分析] {folder_name}: 特定关系人文件为空或格式错误")
        return None, None
    
    # 检查特定关系人文件的列名
    required_specific_columns = ['名称', '身份证号码']
    missing_specific_columns = [col for col in required_specific_columns if col not in specific_df.columns]
    if missing_specific_columns:
        print(f"[特定关系人分析] {folder_name}: 特定关系人文件缺少必要的列: {missing_specific_columns}")
        print(f"当前列名: {list(specific_df.columns)}")
        return None, None

    # 准备特定关系人数据
    relationship_df = specific_df[['名称']].copy()
    if '关系' in specific_df.columns:
        relationship_df['关系'] = specific_df['关系']
    else:
        relationship_df['关系'] = '特定关系人'
    relationship_df['关系类型'] = '特定关系人'
    relationship_df['公司名称'] = None  # 添加空的公司名称列
    print(f"[特定关系人分析] {folder_name}: 找到 {len(relationship_df)} 条特定关系人数据")

    # 获取所有需要匹配的名称和身份证号码
    names_to_match = set(specific_df['名称'].dropna().astype(str).unique())
    id_numbers_to_match = set(specific_df['身份证号码'].dropna().astype(str).unique())
    
    if not names_to_match and not id_numbers_to_match:
        print(f"[特定关系人分析] {folder_name}: 未找到有效的名称或身份证号码数据")
        return None, relationship_df
    
    # 初始化结果DataFrame
    result_rows = []
    
    # 遍历银行流水数据
    for _, row in filtered_bank_df.iterrows():
        name = str(row['名称'])
        counterparty_name = str(row['交易对方名称'])
        id_number = str(row['证件号码'])
        counterparty_id = str(row['交易对方证件号码'])
        
        # 检查当前行的名称或证件号码是否在特定关系人表中（使用精确匹配）
        name_in_specific = name in names_to_match
        counterparty_name_in_specific = counterparty_name in names_to_match
        id_in_specific = id_number in id_numbers_to_match
        counterparty_id_in_specific = counterparty_id in id_numbers_to_match
        
        if name_in_specific or counterparty_name_in_specific or id_in_specific or counterparty_id_in_specific:
            # 找到匹配的特定关系人
            matched_person = None
            if name_in_specific:
                matched_person = specific_df[specific_df['名称'] == name].iloc[0]
            elif counterparty_name_in_specific:
                matched_person = specific_df[specific_df['名称'] == counterparty_name].iloc[0]
            elif id_in_specific:
                matched_person = specific_df[specific_df['身份证号码'] == id_number].iloc[0]
            elif counterparty_id_in_specific:
                matched_person = specific_df[specific_df['身份证号码'] == counterparty_id].iloc[0]
            
            if matched_person is not None:
                # 创建新的行数据
                new_row = row.copy()
                new_row['关系'] = matched_person.get('关系', '特定关系人')
                new_row['关系类型'] = '特定关系人'
                result_rows.append(new_row)
    
    # 创建结果DataFrame
    if result_rows:
        result_df = pd.DataFrame(result_rows)
        print(f"[特定关系人分析] {folder_name}: 找到 {len(result_df)} 条匹配记录")
        return result_df, relationship_df
    else:
        print(f"[特定关系人分析] {folder_name}: 未找到匹配的特定关系人交易记录")
        return None, relationship_df

def analyze_san_shang_list(folder_path, filtered_bank_df):
    """分析三商清单处理结果数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    output_dir = ensure_output_directory(folder_name)
    
    # 从output目录读取三商清单处理结果文件
    san_shang_file = output_dir / "三商清单处理结果.xlsx"
    if not san_shang_file.exists():
        print(f"[三商清单分析] {folder_name}: 三商清单处理结果文件不存在: {san_shang_file}")
        return None, None
    
    san_shang_df = load_excel_file(san_shang_file, header_row=0)
    if san_shang_df is None or san_shang_df.empty:
        print(f"[三商清单分析] {folder_name}: 三商清单处理结果文件为空或格式错误")
        return None, None
    
    # 检查三商清单处理结果文件的列名
    required_columns = ['联系人', '身份', '公司名称']
    missing_columns = [col for col in required_columns if col not in san_shang_df.columns]
    if missing_columns:
        print(f"[三商清单分析] {folder_name}: 三商清单处理结果文件缺少必要的列: {missing_columns}")
        print(f"当前列名: {list(san_shang_df.columns)}")
        return None, None

    # 准备三商清单关系数据
    relationship_df = pd.DataFrame()
    relationship_df['名称'] = san_shang_df['联系人']
    relationship_df['关系'] = san_shang_df['身份']
    relationship_df['关系类型'] = '三商清单'
    relationship_df['公司名称'] = san_shang_df['公司名称']  # 保留三商清单的公司名称
    print(f"[三商清单分析] {folder_name}: 找到 {len(relationship_df)} 条三商清单关系数据")

    # 获取所有需要匹配的联系人
    contacts_to_match = set(san_shang_df['联系人'].dropna().astype(str).unique())
    
    if not contacts_to_match:
        print(f"[三商清单分析] {folder_name}: 未找到有效的联系人数据")
        return None, relationship_df
    
    # 初始化结果DataFrame
    result_rows = []
    
    # 遍历银行流水数据
    for _, row in filtered_bank_df.iterrows():
        name = str(row['名称'])
        counterparty_name = str(row['交易对方名称'])
        
        # 检查当前行的名称或交易对方名称是否在三商清单联系人中
        name_in_san_shang = name in contacts_to_match
        counterparty_name_in_san_shang = counterparty_name in contacts_to_match
        
        if name_in_san_shang or counterparty_name_in_san_shang:
            # 找到匹配的联系人
            matched_contact = None
            if name_in_san_shang:
                matched_contact = name
            else:
                matched_contact = counterparty_name
            
            if matched_contact:
                # 获取对应的身份信息和公司名称
                contact_info = san_shang_df[san_shang_df['联系人'] == matched_contact].iloc[0]
                identity = contact_info['身份']
                company_name = contact_info['公司名称']
                
                # 创建新的行数据
                new_row = row.copy()
                new_row['关系'] = identity
                new_row['关系类型'] = '三商清单'
                new_row['所属公司名称'] = company_name
                result_rows.append(new_row)
    
    # 创建结果DataFrame
    if result_rows:
        result_df = pd.DataFrame(result_rows)
        print(f"[三商清单分析] {folder_name}: 找到 {len(result_df)} 条匹配记录")
        return result_df, relationship_df
    else:
        print(f"[三商清单分析] {folder_name}: 未找到匹配的三商清单交易记录")
        return None, relationship_df

def process_merchant_list(folder_path):
    """处理指定文件夹中的三商清单明细.xlsx文件"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    input_file = folder_path / "三商清单明细.xlsx"
    
    # 修改输出路径到output目录
    output_dir = ensure_output_directory(folder_name)
    output_file = output_dir / "三商清单处理结果.xlsx"
    
    if not input_file.exists():
        print(f"[三商清单处理] {folder_name}: 未找到三商清单明细.xlsx")
        return
    
    try:
        # 读取第二个表，从第三行开始（header=2）
        df = pd.read_excel(input_file, sheet_name=1, header=2)
    except Exception as e:
        print(f"[三商清单处理] {folder_name}: 处理三商清单明细.xlsx时出错: {str(e)}")
        return
    
    results = []
    
    for _, row in df.iterrows():
        company = str(row.iloc[1]).strip()  # 第二列
        people_info = str(row.iloc[4]).strip()  # 第五列
        if not company or company == 'nan':
            continue
        # 公司本身一行
        results.append({'公司名称': company, '联系人': company, '身份': '公司'})
        # 解析联系人和身份
        # 例：胡韶轻（法定代表人、股东）卜凡斋（监事、控股股东、历史法定代表人）
        import re
        pattern = r'(.*?)（(.*?)）'
        matches = re.findall(pattern, people_info)
        for name, identity in matches:
            name = name.strip()
            identity = identity.strip()
            if name and identity:
                results.append({'公司名称': company, '联系人': name, '身份': identity})
    
    if results:
        # 保存结果
        df_out = pd.DataFrame(results)
        df_out.to_excel(output_file, index=False)
        print(f"[三商清单处理] {folder_name}: 处理完成，找到 {len(results)} 条记录，结果已保存到三商清单处理结果.xlsx")
    else:
        print(f"[三商清单处理] {folder_name}: 在三商清单明细.xlsx中未找到有效数据")

def summarize_transactions(folder_path):
    """汇总交易金额数据"""
    folder_path = Path(folder_path)
    folder_name = folder_path.name
    
    # 从output目录读取分析结果文件
    output_dir = ensure_output_directory(folder_name)
    analysis_file = output_dir / "交易明细.xlsx"
    summary_file = output_dir / "交易汇总.xlsx"
    
    if not analysis_file.exists():
        print(f"[交易汇总] {folder_name}: 分析结果文件不存在: {analysis_file}")
        return None
    
    # 读取分析结果文件
    df = load_excel_file(analysis_file, header_row=0)
    if df is None or df.empty:
        print(f"[交易汇总] {folder_name}: 分析结果文件为空或格式错误")
        return None
    
    # 检查必要的列是否存在
    required_columns = ['名称', '交易对方名称', '交易金额', '关系', '关系类型', '借贷标志']
    missing_columns = [col for col in required_columns if col not in df.columns]
    if missing_columns:
        print(f"[交易汇总] {folder_name}: 分析结果文件缺少必要的列: {missing_columns}")
        print(f"当前列名: {list(df.columns)}")
        return None
    
    # 如果缺少所属公司名称列，添加一个空列
    if '所属公司名称' not in df.columns:
        df['所属公司名称'] = None
    
    try:
        # 确保交易金额列为数值类型
        df['交易金额'] = pd.to_numeric(df['交易金额'], errors='coerce')
        
        # 创建一个新的DataFrame来存储交易汇总
        summary_rows = []
        
        # 获取所有唯一的交易对（按字母顺序排序）
        pairs = set()
        for _, row in df.iterrows():
            name1, name2 = sorted([row['名称'], row['交易对方名称']])
            pairs.add((name1, name2))
        
        # 对每对交易方计算汇总金额
        for name1, name2 in pairs:
            # 获取两个方向的所有交易
            transactions1 = df[
                (df['名称'] == name1) & 
                (df['交易对方名称'] == name2)
            ].copy()
            
            transactions2 = df[
                (df['名称'] == name2) & 
                (df['交易对方名称'] == name1)
            ].copy()
            
            if transactions1.empty and transactions2.empty:
                continue
            
            # 计算name1到name2的净转出
            out1 = transactions1[transactions1['借贷标志'] == '出']['交易金额'].sum()
            in1 = transactions1[transactions1['借贷标志'] == '进']['交易金额'].sum()
            net1 = out1 - in1  # name1净转出给name2的金额
            
            # 计算name2到name1的净转出
            out2 = transactions2[transactions2['借贷标志'] == '出']['交易金额'].sum()
            in2 = transactions2[transactions2['借贷标志'] == '进']['交易金额'].sum()
            net2 = out2 - in2  # name2净转出给name1的金额
            
            # 选择净转出金额较大的那一方
            if net1 >= net2:
                # 使用name1到name2的交易记录
                first_record = transactions1.iloc[0] if not transactions1.empty else transactions2.iloc[0]
                summary_rows.append({
                    '名称': name1,
                    '交易对方名称': name2,
                    '关系': first_record['关系'],
                    '关系类型': first_record['关系类型'],
                    '所属公司名称': first_record['所属公司名称'],
                    '转出金额': out1,
                    '转入金额': in1,
                    '净转出金额': net1,
                    '对方转出金额': out2,
                    '对方转入金额': in2,
                    '对方净转出金额': net2,
                    '净转出差额': net1 - net2  # 大的净转出减去小的
                })
            else:
                # 使用name2到name1的交易记录
                first_record = transactions2.iloc[0] if not transactions2.empty else transactions1.iloc[0]
                summary_rows.append({
                    '名称': name2,
                    '交易对方名称': name1,
                    '关系': first_record['关系'],
                    '关系类型': first_record['关系类型'],
                    '所属公司名称': first_record['所属公司名称'],
                    '转出金额': out2,
                    '转入金额': in2,
                    '净转出金额': net2,
                    '对方转出金额': out1,
                    '对方转入金额': in1,
                    '对方净转出金额': net1,
                    '净转出差额': net2 - net1  # 大的净转出减去小的
                })
        
        # 创建汇总DataFrame
        summary_df = pd.DataFrame(summary_rows)
        
        # 按净转出差额降序排序
        if not summary_df.empty:
            summary_df = summary_df.sort_values('净转出差额', ascending=False)
        
        # 保存汇总结果
        summary_df.to_excel(summary_file, index=False)
        print(f"[交易汇总] {folder_name}: 汇总完成，找到 {len(summary_df)} 条记录，结果已保存到交易汇总.xlsx")
        return summary_df
    except Exception as e:
        print(f"[交易汇总] {folder_name}: 处理数据时出错: {str(e)}")
        return None

def main():
    """主函数"""
    # 获取所有源文件夹
    source_folders = get_source_folders()
    
    if not source_folders:
        print("[主程序] 未找到源文件夹")
        return
    
    # 处理每个文件夹
    for folder in source_folders:
        print(f"\n[主程序] 开始处理文件夹: {folder.name}")
        output_dir = ensure_output_directory(folder.name)
        relationship_data = []
        
        # 第一阶段：处理三商清单
        print(f"\n=== 第一阶段：处理三商清单 ===")
        print(f"[主程序] 处理文件夹 {folder.name} 的三商清单")
        process_merchant_list(folder)
        
        # 第二阶段：关系网络分析
        print(f"\n=== 第二阶段：关系网络分析 ===")
        
        # 加载并筛选银行流水数据
        filtered_bank_df = load_filtered_bank_data(folder)
        if filtered_bank_df is None:
            print(f"[主程序] {folder.name}: 银行流水数据加载失败，跳过此文件夹的处理")
            continue
        
        print(f"[主程序] {folder.name}: 成功加载银行流水数据，开始进行各项分析")
        
        # 分析各种关系并收集关系数据
        relative_result_df, relative_relationship_df = analyze_relative_network(folder, filtered_bank_df)
        employment_result_df, employment_relationship_df = analyze_employment_network(folder, filtered_bank_df)
        specific_result_df, specific_relationship_df = analyze_specific_relationships(folder, filtered_bank_df)
        san_shang_result_df, san_shang_relationship_df = analyze_san_shang_list(folder, filtered_bank_df)
        
        # 合并所有关系数据
        relationship_dfs = []
        if relative_relationship_df is not None:
            relationship_dfs.append(relative_relationship_df)
        if employment_relationship_df is not None:
            relationship_dfs.append(employment_relationship_df)
        if specific_relationship_df is not None:
            relationship_dfs.append(specific_relationship_df)
        if san_shang_relationship_df is not None:
            relationship_dfs.append(san_shang_relationship_df)
        
        if relationship_dfs:
            # 合并所有关系数据并删除重复行
            combined_relationship_df = pd.concat(relationship_dfs, ignore_index=True)
            combined_relationship_df = combined_relationship_df.drop_duplicates()
            
            # 保存关系总表
            relationship_summary_file = output_dir / "关系总表.xlsx"
            combined_relationship_df.to_excel(relationship_summary_file, index=False)
            print(f"[主程序] {folder.name}: 关系总表生成完成，共 {len(combined_relationship_df)} 条记录")
        
        # 合并分析结果
        result_dfs = []
        if relative_result_df is not None:
            result_dfs.append(relative_result_df)
        if employment_result_df is not None:
            result_dfs.append(employment_result_df)
        if specific_result_df is not None:
            result_dfs.append(specific_result_df)
        if san_shang_result_df is not None:
            result_dfs.append(san_shang_result_df)
            
        if result_dfs:
            combined_df = pd.concat(result_dfs, ignore_index=True)
            output_file = output_dir / "交易明细.xlsx"
            combined_df.to_excel(output_file, index=False)
            print(f"[主程序] {folder.name}: 分析完成，共找到 {len(combined_df)} 条匹配记录")
            
            # 第三阶段：生成交易汇总
            print(f"\n=== 第三阶段：生成交易汇总 ===")
            print(f"[主程序] {folder.name}: 开始生成交易汇总")
            summarize_transactions(folder)
            print(f"[主程序] {folder.name}: 所有处理步骤已完成\n")
        else:
            print(f"[主程序] {folder.name}: 所有分析均未找到匹配数据，不生成结果文件")
            print(f"[主程序] {folder.name}: 处理完成\n")
            continue
    
    print("\n[主程序] 所有文件夹处理完成")

if __name__ == "__main__":
    main() 